package com.lhkj.iams.wechat.service.impl;


import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.binarywang.wxpay.bean.notify.SignatureHeader;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyV3Result;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.lhkj.iams.wechat.config.mp.WxMpConfiguration;
import com.lhkj.iams.wechat.config.mp.bo.WxParsePayResultBo;
import com.lhkj.iams.wechat.model.dto.WxJsapiOrderRequest;
import com.lhkj.iams.wechat.service.WxMpPayService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class WxMpPayServiceImpl implements WxMpPayService {

    private Logger log = LoggerFactory.getLogger(WxMpPayServiceImpl.class);

    @Resource(name = "wxPayService")
    private WxPayService wxPayService;

    /**
     * JSAPI下单
     */
    @Override
    public WxPayUnifiedOrderV3Result.JsapiResult jsApiOrder(WxJsapiOrderRequest payParams) throws WxPayException {
        // JSAPI下单
        String mchId = StringUtils.defaultIfBlank(payParams.getMchid(), WxMpConfiguration.DEFAULT_MCH_ID);
        WxPayUnifiedOrderV3Request payRequest = new WxPayUnifiedOrderV3Request();
        payRequest.setAppid(payParams.getAppId());
        // 支付者
        payRequest.setPayer(new WxPayUnifiedOrderV3Request.Payer().setOpenid(payParams.getOpenid()));
        // 商户系统订单编号
        payRequest.setOutTradeNo(payParams.getOutTradeNo());
        // 订单金额
        payRequest.setAmount(new WxPayUnifiedOrderV3Request.Amount()
                // 总金额 以分为单位
                .setTotal(payParams.getTotal())
                // 货币类型
                .setCurrency(payParams.getCurrency()));
        // 附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据，这里将商户订单号返回
        payRequest.setAttach(payParams.getOutTradeNo());
        //商品描述
        payRequest.setDescription(payParams.getDescription());
        // 回调地址
        payRequest.setNotifyUrl(payParams.getNotifyUrl());
        WxPayService target = wxPayService.switchoverTo(mchId);
//        log.info("微信支付配置：{}", JSON.toJSONString(target.getConfig()));
        log.info("微信支付参数：{}", JSON.toJSONString(payRequest));
        return target.createOrderV3(TradeTypeEnum.JSAPI, payRequest);
    }


    /**
     * 解析微信支付回调结果
     */
    @Override
    public WxPayNotifyV3Result.DecryptNotifyResult parseOrderNotifyV3Result(WxParsePayResultBo parsePayResultBo) throws WxPayException, JsonProcessingException {
        String mchId = StringUtils.defaultIfBlank(parsePayResultBo.getMchId(), WxMpConfiguration.DEFAULT_MCH_ID);
        WxPayService target = wxPayService.switchoverTo(mchId);
        SignatureHeader header = new SignatureHeader(
                parsePayResultBo.getTimeStamp(),
                parsePayResultBo.getNonce(),
                parsePayResultBo.getSignature(),
                parsePayResultBo.getSerial());
        log.info("微信回调解析SignatureHeader：{}", new ObjectMapper().writeValueAsString(header));
        log.info("微信回调解析notifyData：{}", parsePayResultBo.getNotifyData());
        WxPayNotifyV3Result wxPayNotifyV3Result = target.parseOrderNotifyV3Result(parsePayResultBo.getNotifyData(), header);
        log.info("微信回调解析结果：{}", new ObjectMapper().writeValueAsString(wxPayNotifyV3Result.getResult()));
        return wxPayNotifyV3Result.getResult();
    }
}
